/*
* Copyright 2018 Shanxi Lu'an Taihang Laihui Net Tech co.,LTD.
*/
package com.laihuichuxing.wyc.provider;

import com.alibaba.dubbo.config.annotation.Service;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.laihuichuxing.caocao.CaocaoClient;
import com.laihuichuxing.caocao.CaocaoConfig;
import com.laihuichuxing.caocao.DefaultCaocaoClient;
import com.laihuichuxing.caocao.request.CaocaoCancelOrderRequest;
import com.laihuichuxing.caocao.request.CaocaoQueryOrderDetailRequest;
import com.laihuichuxing.caocao.response.CaocaoCancelOrderResponse;
import com.laihuichuxing.caocao.response.CaocaoQueryOrderDetailResponse;
import com.laihuichuxing.common.util.JsonUtil;
import com.laihuichuxing.config.ResponseCode;
import com.laihuichuxing.order.wy.api.WyOrderServerApi;
import com.laihuichuxing.order.wy.entity.WyOrderEntity;
import com.laihuichuxing.wyc.dao.WyOrderDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description:
 *
 * @author: Qinxuefeng
 * @since: 1.0
 * Create Date Time: 2018/11/19 18:24
 * Update Date Time:
 */
@Slf4j
@Service(version = "1.0.0",interfaceClass = WyOrderServerApi.class)
public class WyOrderServerProvider implements WyOrderServerApi {
    @Autowired
    private WyOrderDao wyOrderDao;
    /**
     * 初始化
     */
    private CaocaoClient caocaoClient;

    {
        caocaoClient = new DefaultCaocaoClient(CaocaoConfig.FALSE);
    }
    @Override
    public List<WyOrderEntity> findPageByPassengerId(String s, String s1, Integer integer, Integer integer1) {
        return wyOrderDao.findPageByPassengerId(s,s1,integer,integer1);
    }

    @Override
    public Map<String, Object> insert(WyOrderEntity wyOrderEntity) {
        Integer insert = wyOrderDao.insert(wyOrderEntity);
        //Integer insert = wyOrderDao.findCancaleNum("123");
         if(insert==1){
             return JsonUtil.getJson(ResponseCode.SUCCESS, "新增成功");
        }
        return JsonUtil.getJson(ResponseCode.FAIL, "新增失败");
    }
    @Override
    public WyOrderEntity findOrderById(String s) {
        return wyOrderDao.findOrderById(s);
    }

    @Override
    public WyOrderEntity findOrderByPassengerId(String s) {
        return wyOrderDao.findOrderByPassengerId(s);
    }

    @Override
    public Map<String, Object> findDriverInfo(String orderNo, String orderStatus) {
        WyOrderEntity wyOrderEntity = new WyOrderEntity();
        wyOrderEntity.setOrderNo(orderNo);
        wyOrderEntity.setOrderStatus(orderStatus);
        return wyOrderDao.findDriverInfo(wyOrderEntity);
    }

    @Override
    public Map<String, Object> findCaocaoOrder(String orderNo) throws Exception{
        return getStringObjectMap(orderNo,null);
    }

    @Override
    public Map<String, Object> findCommitCaocaoPlain(String orderNo, String text) throws Exception {
        return getStringObjectMap(orderNo,text);
    }

    @Override
    public Integer saveOrderPayTable(WyOrderEntity wyOrderEntity) {
        return wyOrderDao.saveOrderPayTable(wyOrderEntity);
    }

    @Override
    public Integer updateOrderPayTable(WyOrderEntity wyOrderEntity) {
        return wyOrderDao.updateOrderPayTable(wyOrderEntity);
    }

    @Override
    public Map<String, Object> cancalOrder(WyOrderEntity wyOrderEntity, String userId) {
        try{
        WyOrderEntity orderById = wyOrderDao.findOrderById(wyOrderEntity.getOrderNo());
        Integer flag= Integer.valueOf(orderById.getFlag());
        Integer state= Integer.valueOf(orderById.getOrderStatus());
        wyOrderEntity.setCancelTime(new Date().toString());
        if (flag==2) {
            //曹操取消订单
            if (Caocaocancel(wyOrderEntity, orderById)) return JsonUtil.getJson(ResponseCode.FAIL, "请求失败");
        }else {
            //判断订单状态
            if (state >= 3) {
                return JsonUtil.getJson(ResponseCode.FAIL, "司机已发车，无法取消");
            }
            if (insertCancalLog(wyOrderEntity, userId)) return JsonUtil.getJson(ResponseCode.FAIL, "当日取消超过3次");
        }
            //修改订单状态
            if (updateOrderStatus(wyOrderEntity)) return JsonUtil.getJson(ResponseCode.FAIL, "取消订单失败,请稍后再试");
            return JsonUtil.getJson(ResponseCode.SUCCESS, "取消订单成功");
        } catch (Exception e) {
            log.error("取消订单接口异常,异常信息为:{}",e.getMessage());
            return JsonUtil.getJson(ResponseCode.SERVER_ERROR, "服务器异常");
        }
    }

    @Override
    public String selectPassengerOrderId(String s, int i) {
        return wyOrderDao.selectPassengerOrderId(s,i);
    }

    @Override
    public String selectPassengerMobile(String s, int i) {
        return wyOrderDao.selectPassengerMobile(s,i);
    }

    @Override
    public String selectMobileByOrderId(String s) {
        return wyOrderDao.selectMobileByOrderId(s);
    }

    @Override
    public Map<String, Object> selectOrder(String s, int i) {
        return wyOrderDao.selectOrder(s,i);
    }

    @Override
    public void updateDriver(String driverId, String orderId) {
        wyOrderDao.updateWyOrder(orderId, driverId);
    }

    @Override
    public void updateFlage(String orderNO, String orderId, int flag) {
        wyOrderDao.updateFlage(orderNO, orderId, flag);
    }

    /**
     * Description:  修改订单状态
     * @param  wyOrderEntity
     * @return  boolean
     * @author QinXueFeng
     * Create Date Time: 2018/11/20 17:48
     * Update Date Time:
     */
    private boolean updateOrderStatus(WyOrderEntity wyOrderEntity) {
        wyOrderEntity.setOrderStatus("8");
        Integer cout=wyOrderDao.update(wyOrderEntity);
        if (cout == 0) {
            TransactionAspectSupport.currentTransactionStatus()
                    .setRollbackOnly();
            return true;
        }
        return false;
    }
    /**
     * Description: 增加取消日志
     * @param  wyOrderEntity
     * @param  userId
     * @return  boolean
     * @author QinXueFeng
     * Create Date Time: 2018/11/20 17:49
     * Update Date Time:
     */
    private boolean insertCancalLog(WyOrderEntity wyOrderEntity, String userId) {
        wyOrderEntity.setOrderStatus("3");
        WyOrderEntity orderLtState = wyOrderDao.findOrderLtState(wyOrderEntity);
        //取消订单记录，只添加接单后取消的记录
        if (orderLtState != null) {
            //当日取消次数
            int count = wyOrderDao.findCancaleNum(userId);
            if (count >= 3) {
                return true;
            }
            int  orderlog = wyOrderDao.insertCancalLog(userId);
        }
        return false;
    }
    /**
     * Description: 曹操取消订单
     * @param  wyOrderEntity
     * @param  orderById
     * @return boolean
     * @author QinXueFeng
     * Create Date Time: 2018/11/20 17:49
     * Update Date Time:
     */
    private boolean Caocaocancel(WyOrderEntity wyOrderEntity, WyOrderEntity orderById) throws Exception {
        CaocaoCancelOrderRequest caocaoRequest = new CaocaoCancelOrderRequest();
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("order_id", orderById.getCaoOrderId());
        paramMap.put("cancel_code", wyOrderEntity.getCancelTypeCode());
        paramMap.put("cancel_reason", wyOrderEntity.getCancelReason());
        caocaoRequest.setTextParams(paramMap);
        // 执行请求,获取返回数据
        CaocaoCancelOrderResponse caocaoResponse = caocaoClient.execute(caocaoRequest);
        if (!caocaoResponse.isSuccess()&& !("订单已取消").equals(caocaoResponse.getMsg())) {
            // 获取错误信息
            return true;
        }
        return false;
    }
    private Map<String, Object> getStringObjectMap(String orderNo,String text) throws Exception {
        String caocaoOrderNo = wyOrderDao.getCaocaoOrderNo(orderNo);
        CaocaoQueryOrderDetailRequest caocaoRequest = new CaocaoQueryOrderDetailRequest();
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("order_id", caocaoOrderNo);
        if(!Strings.isNullOrEmpty(text)){
            paramMap.put("content", text);
        }
        caocaoRequest.setTextParams(paramMap);
        // 执行请求,获取返回数据
        CaocaoQueryOrderDetailResponse caocaoResponse = caocaoClient.execute(caocaoRequest);
        Map<String,Object> map = Maps.newHashMap();
        map.put("caoCaoResponse",caocaoResponse);
        return map;
    }
}
